import Cookies from 'js-cookie'
export const TokenKey = 'authorized-token'
export const TokenHeader = 'token'
export const setToken = (data: Token) => {
  const { accessToken, expires, refreshToken, refreshExpirationTime } = data
  if (refreshExpirationTime > new Date().getTime()) {
    const cookieString = JSON.stringify({
      accessToken,
      expires,
      refreshToken,
      refreshExpirationTime
    })
    Cookies.set(TokenKey, cookieString, {
      expires: new Date(refreshExpirationTime)
    })
  }
}

export const clearToken = () => {
  Cookies.remove(TokenKey)
}

export const getToken = (): Token => {
  const tokenStr = Cookies.get(TokenKey)
  if (tokenStr) {
    return JSON.parse(tokenStr)
  } else {
    return {} as Token
  }
}
